(function(){
	$("pre").addClass("prettyprint");
	prettyPrint();
	
	var elements = $('#comments .etag');
	var $nickname = $(elements[0]);
	var $email = $(elements[1]);
	var $url = $(elements[2]);
	var $content = $(elements[3]);
	var $submit = $(elements[4]);
	var $postId = $(elements[5]);
	
	var $reply_dlg = $('#reply_dlg');
	
	elements = $('#reply_dlg .etag');
	var $replynickname = $(elements[0]);
	var $replyemail = $(elements[1]);
	var $replyurl = $(elements[2]);
	var $replycontent = $(elements[3]);
	var $replysubmit = $(elements[4]);
	var $replycancle = $(elements[5]);
	var commentParentId = 0;
	
	$replycancle.click(function(){
		$reply_dlg.css({'display':'none'});
	});
	
	$replysubmit.click(function(){
		if(!validateReply()){
			return;
		}
		$.post('/post/json/postcomment',getReplyPostData(),function(result){
			if(!!result){
				$reply_dlg.css({'display':'none'});
				$('#subcommentlist-' + commentParentId).prepend(result);
			}else{
				alert('error');
			}
		})
	});
	
	var $commentlist = $('#commentlist');
	$submit.click(function(){
		if(!validate()){
			return;
		}
		$.post('/post/json/postcomment',getPostData(),function(result){
			if(!!result){
				$commentlist.prepend(result);
			}
		})
	});
	
	function getPostData(){
		var data = {};
		data['postId'] = $postId.val();
		data['nickname'] = $nickname.val();
		data['email'] = $email.val();
		data['url'] = $url.val();
		data['content'] = $content.val();
		return data;
	}
	
	function getReplyPostData(){
		var data = {};
		data['postId'] = $postId.val();
		data['nickname'] = $replynickname.val();
		data['email'] = $replyemail.val();
		data['url'] = $replyurl.val();
		data['content'] = $replycontent.val();
		data['parentId'] = commentParentId;
		return data;
	}
	
	var emailPattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
	
	function validate(){
		if(!$.trim($nickname.val())){
			alert('昵称不能为空!');
			$nickname.focus();
			return false;
		}
		if(!emailPattern.test($.trim($email.val()))){
			alert('email格式不正确!');
			$email.focus();
			return false;
		}
		if(!$.trim($content.val())){
			alert('评论内容不能为空!');
			$content.focus();
			return false;
		}
		return true;
	}
	
	function validateReply(){
		if(!$.trim($replynickname.val())){
			alert('昵称不能为空!');
			$replynickname.focus();
			return false;
		}
		if(!emailPattern.test($.trim($replyemail.val()))){
			alert('email格式不正确!');
			$replyemail.focus();
			return false;
		}
		if(!$.trim($replycontent.val())){
			alert('评论内容不能为空!');
			$replycontent.focus();
			return false;
		}
		return true;
	}
	
	window.Comment = {
		reply : function(commentId, parentId){
			commentParentId = parentId > 0 ? parentId:commentId;
			$('#content-'+commentId).after($reply_dlg);
			$reply_dlg.css({'display':''});
		}
	};
	
})();